<template>
	<div>
		<el-form class="query-form" :model="query_params">
			<el-row>
		    <el-col class="query-item" :span="6">
					<el-form-item label="卡券名称" prop="name">
						<el-input v-model="query_params.name" placeholder="请输入卡券名称" autocomplete="off" />
					</el-form-item>
				</el-col>
				<el-col class="query-item" :span="6">
					<el-form-item >
						<el-button type="primary" @click="search">搜索</el-button>
					</el-form-item>
				</el-col>

		  </el-row>
		</el-form>
		<el-row class="add-box-css"><el-button type="primary" @click="info_operation()">新增</el-button></el-row>
		<el-table :data="tableData" border style="width: 100%">
		    <el-table-column label="序号" width="180" >
				<template #default="scope">
		            {{scope.$index+1}}
		        </template>
		    </el-table-column>
		    <el-table-column prop="name" label="卡券名称" width="180" />
		    <el-table-column prop="price" label="卡券价格" width="180" />
		    <el-table-column prop="desc" label="卡券介绍" width="180" />
				<!-- <el-table-column prop="activity_name" label="所属活动" width="180" /> -->
		    <el-table-column prop="content" label="服务内容" >
					<template v-slot:default="scope">
								{{getServideNum(scope.row)}}
					</template>
				</el-table-column>
				<!-- <el-table-column prop="amount" label="使用次数" width="180" /> -->
		    <el-table-column prop="createdAt" label="创建时间" />
				<!-- <el-table-column prop="disable" label="状态" >
					<template #default="scope">
							{{getStatus(scope.row)}}
					</template>
				</el-table-column> -->
		    <!-- <el-table-column  label="激活" >
		    	<template #default="scope">
		    		<el-switch  v-model="scope.row.disable" @click="confirm(scope.row)"/>
		      </template>
				</el-table-column> -->
				<el-table-column  label="操作" >
		    	<template #default="scope">
		    		<el-button type="primary" size="small" @click="info_operation(scope.row)">编辑</el-button>
		    		<el-button type="danger" size="small" @click="del_fun(scope.row)">删除</el-button>
		      </template>
				</el-table-column>
		</el-table>
		<div class="pagination_box">
			<el-pagination background layout="prev, pager, next"  :total="total" @current-change="handleCurrentChange" />
		</div>
		<!-- 新增 & 编辑 -->
		<div>
			<el-drawer v-model="drawer" size='60%' :with-header="true">
					<template #title>
						<h4>新增/编辑 卡券</h4>
					</template>
			    <template #default>
			      <div>
							<el-form
							    ref="ruleFormRef"
							    :model="ruleForm"
							    status-icon
							    :rules="rules"
							    label-width="120px"
							    class="demo-ruleForm"
							    :loading="loading"
							  >
							    <el-form-item label="卡券名称" prop="name">
							      <el-input v-model="ruleForm.name"  autocomplete="off" />
							    </el-form-item>
							    <el-form-item label="服务项目" prop="service" :rules="[
						        { required: true, message: '请选择服务项目',trigger: 'blur' }
						      ]">
							      <!-- <el-input v-model="ruleForm.content"  autocomplete="off" /> -->
										<el-select
								      v-model="ruleForm.service"
								      multiple
								      placeholder="请选择服务内容"
								      style="width: 240px"
								    >
								      <el-option
								        v-for="item in service_items"
								        :key="item.id"
								        :label="item.name"
								        :value="item.id"
								      />
								    </el-select>
							    </el-form-item>
									<el-form-item label="所属活动" prop="event_id" :rules="[
						        { required: true, message: '请选择所属活动',trigger: 'blur' }
						      ]">
										<el-select v-model="ruleForm.event_id" class="m-2" placeholder="请选择所属活动">
										    <el-option
										        v-for="item in activityList"
										        :key="item.id"
										        :label="item.name"
										        :value="item.id"
										      />
										</el-select>
									</el-form-item>
									<el-form-item label="卡券图片" prop="coupon_img">
								     <el-upload
											    v-model:file-list="coupon_img"
											    :action="action"
											    :auto-upload="true"
											    list-type="picture-card"
											    :on-preview="handlePictureCardPreview"
											    :on-remove="handleRemove"
											    :on-change="handleChange(0,'coupon_img')"
											    :http-request="uploadAction"
											  >
										    <el-icon><Plus /></el-icon>
										 </el-upload>
									</el-form-item>
									<el-form-item label="卡券说明" prop="desc">
							      <el-input v-model="ruleForm.desc" type="textarea"  autocomplete="off" />
							    </el-form-item>
									<el-form-item label="卡券价格" prop="price">
							      <el-input v-model="ruleForm.price"  autocomplete="off" />
							    </el-form-item>
								<!-- <el-form-item label="服务次数" prop="count">
							      <el-input v-model="ruleForm.count"  autocomplete="off" />
							    </el-form-item> -->
								<!-- <el-form-item label="是否禁用" prop="disable">
							      <el-switch v-model="ruleForm.disable" />
							    </el-form-item> -->
							    <el-form-item >
							      <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
							    </el-form-item>
							</el-form>
			      </div>
			    </template>
			  </el-drawer>
		</div>
		<!-- 图片预览 -->
		<el-dialog v-model="dialogVisible">
	    <img w-full :src="dialogImageUrl" alt="Preview Image" />
	  </el-dialog>
	</div>
</template>
<script type="text/javascript">
	import {  ElMessageBox ,ElMessage,FormInstance,FormRules } from 'element-plus'
	import api from "@/api/store/store"
	export default {
		data(){
			return {
				action:'',
				queryForm:{},
				query_params:{
					current:1,
					size:10
				},
				tableData:[],
				total:0,
				drawer:false,
				// 表单
				ruleFormRef:{},
				ruleForm :{},
				rules:{
				  name: [
				    { required: true, message: '请输入卡券名称', trigger: 'blur' },
				  ],
					price: [
				    { required: true, message: '请输入卡券名称', trigger: 'blur' }
				  ],
				},
				//服务列表
				services:'',
				service_items:[],
				//活动列表
				activity:'',
				activityList:[],
				//门店列表
				storeList:[],
				//卡券图片
				headImg:[],
				loading:false,
				list_type:'',
				//卡券图片
				coupon_img:[],
				//预览图片
				dialogVisible:false,
				dialogImageUrl:'',//预览地址,
			}
		},
		methods:{
			del_fun(row){ // 删除数据
				ElMessageBox.alert('确定要删除该数据吗？', '提示', {
				    confirmButtonText: '确定',
				    callback:async action => {
					  if(action == "confirm"){
					  		const res = await api.delCoupon(row);
					  		if(res?.code == 200) {
					  		  ElMessage({
						        type: 'success',
						        message: '删除成功',
						      })
						      this.getList();
					  		}
					  }
				      
				    },
				 })
			},
			async submitForm(val){//提交表单
				this.cardParams();//梳理参数
				// console.log(this.ruleForm);return
				const res = await api.addCoupon(this.ruleForm)
				if(res.code == 200) {
					ElMessage({
				        type: 'success',
				        message: '操作成功',
				    })
				    this.drawer = false;
					this.getList();
				}
				else{
					console.log(res)
					ElMessage({
				        type: "error",
				        message: res.response.data.message,
				    })
				    this.getList();
				}
			},
			cardParams(){ // 梳理数据
				//文件相关
				// const fields=['img'];//文件名
				// var prefix="coupon_";
				// console.log(this.coupon_img)
				// for(let val of fields){
				// 	let name=prefix+val;
				// 	if(this[name].length>0){
				// 			let new_list = [];
				// 			for(let item of this[name]){
				// 				if(item.url){
				// 					new_list.push(item.url)
				// 				}
				// 			}
				// 			this.ruleForm[val] = new_list.join(",")
				// 	}
				// }
				if(this.coupon_img.length > 0){
					let new_list= []
					for(let item of this.coupon_img){
						if(item.url){
							new_list.push(item.url)
						}
					}
					this.ruleForm.coupon_img = new_list.join("|")
				}
				
				//控制传参
				if(this.ruleForm.createdAt) delete this.ruleForm.createdAt
				if(this.ruleForm.updatedAt) delete this.ruleForm.updatedAt

				this.ruleForm.price = parseFloat(this.ruleForm.price)
				// this.ruleForm.pricing = parseFloat(this.ruleForm.pricing)
				// 服务相关
				if(this.ruleForm.service.length > 0) this.ruleForm.service_id = this.ruleForm.service.join(",");
				// 价格乘以100
				this.ruleForm.price = parseFloat((parseFloat(this.ruleForm.price)*100).toFixed(2))
				console.log(typeof parseFloat(this.ruleForm.price) )

			},
			search(){
				this.query_params.current=1;
				this.query_params.size=10;
				this.getList()
			},
			info_operation(row){//编辑 & 新增 服务
				// console.log(111);returns
				//清空选项
				this.services='';
				this.activity="";
				this.coupon_img = [];
				//打开面板
				this.drawer=true
				if(row){//编辑
						// console.log(row)s
						// 填充值
						// for(let prop in row){
						// 	let num_arr=["price"];//数字化
						// 	if(num_arr.includes(prop)){
						// 			row[prop]=parseFloat(row[prop])
						// 	}
						// 	this.ruleForm[prop]=row[prop];
						// }
						this.ruleForm = row
						// //梳理文件数据
						this.cardDataEdit(row)
				}
				else{//新增
					this.ruleForm={};
					//清除所有文件数组
					this.clearFiles()
				}
			},
			clearFiles(){
				const fields=['headImg'];//文件字段名
				var prefix="coupon_";//前缀
				for(let val of fields){
					let name=prefix+val
					this[name]=[];
				}
			},
			cardDataEdit(row){//梳理文件数据
				if(row.coupon_img){
					let coupon_img = row.coupon_img.split("|")
					var new_list=[];
					for(let val of coupon_img){
						let new_img = {
								content: val,
								url: val
						}
						new_list.push(new_img)
					}
					this.coupon_img = new_list;
				}
				if(row.service_id) {
					this.ruleForm.service = row.service_id.split(",")
				}
			},
			getServideNum(row){
				var count = 0;
				if(row.service_id) count = row.service_id.split(",").length
				return `共${count}条服务`
			},
			getStatus(row){//查询状态
				var str="正常"
				if(!row.disable){
					str="已禁止"
				}
				return str
			},
			handleCurrentChange(val){//分页
				this.query_params.current=val;
				this.getList();
			},
			getList(){//获取卡券列表
				api.getCouponList(this.query_params).then(res=>{
					if(res.code==200){
						res.data.records = res.data.records.map((item,i) => {
							if(item.price) {
								item.price = (parseFloat(item.price)/100).toFixed(2)
							}	
							return item
						})
						this.tableData=res.data.records;
						if(this.total<1){
							this.total=res.data.total
						}
						//headImg
            // if (res.data.headImg){
            //     var headImgs = this.ruleForm.headImg.split(",");
            //     var new_logo_list=[];
            //     for (let val of headImgs){
            //         let new_img = {
            //             content: val,
            //             url: val
            //         }
            //         new_logo_list.push(new_img)
            //     }
            //     this.headImg = new_logo_list;
            // }
						
					}
				})
			},
			getOtherInfo(){
				const params = {
					current:1,
					size:1000
				}
				//获取服务列表
				api.getServiceList(params).then(res=>{
						this.service_items=res.data.records
				})
				//获取活动列表
				api.getActivityList(params).then(res=>{
						this.activityList=res.data.records
				})
				//获取门店列表
				// api.getStoreList({}).then(res=>{
				// 		this.storeList = res.data
				// })
			},
			//图片上传
			handlePictureCardPreview(uploadFile){//预览文件
				this.dialogImageUrl=uploadFile.url
				this.dialogVisible=true
			},
			handleRemove(uploadFile, uploadFiles){

			},
			handleChange(i,type){
				this.list_type=type
				// if(type=='normsList'){
				// 	this.current_norms=i
				// }
			},
			async uploadAction(file){//文件上传
					file.status = 'uploading';
					file.message = '上传中...';
					//开始上传
					const content = new FormData();
					//上传图片需要转换二进制这里要用到FormData
					content.append("file", file.file);
					const res=await this.$API.upload(content);
					if(res.code==200){
						file.status = 'done';
						file.message = '上传成功';
						file.url = res.data;
					}
					else{
						file.status = 'failed';
						file.message = '上传失败';
					}
					//重新赋值  img/视频
					for(let item of this[this.list_type]){
						if(item.uid==file.file.uid){
							item.url=file.url
						}
					}
			},
		},
		mounted(){
			this.getList();
			this.getOtherInfo();
		}
	}
</script>
<style type="text/css">
	.pagination_box{
		    text-align: center;
		    display: flex;
		    justify-content: center;
		    width: 100%;
	}
	.query-item{
		margin-right:10px
	}
	.query-form{
		    padding:20px;
				    padding-bottom: 0px;
	}
	.add-box-css{
		width:100%;
		align-items: end;
    justify-content: end;
    padding: 0px 1rem 1rem 0px;
	}
</style>
